package scigest.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import thredds.catalog.InvCatalogFactory;
import thredds.catalog.InvCatalogImpl;
import thredds.catalog.InvCatalogRef;

/**
 * 
 * A class that implements xref linking for catalog file
 * 
 * @author Feiyi Wang
 *
 */
public class CatalogXref {

	private static Logger logger = LoggerFactory.getLogger(CatalogXref.class);
	
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		
		if ((args.length < 2) || (3 < args.length)) {
			logger.error("We need three arguments: catalog file to be merged, main catalog file, 'add' or 'remove'");
			System.exit(1);
		}

		List<String> catalogList = readCatalogFile(args[0]);
		
		InvCatalogFactory factory = new InvCatalogFactory("default", true);
		URI cataURI = null;
		try {
			String uriString = args[1];
			cataURI = new URI(uriString);
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		InvCatalogImpl catalog = (InvCatalogImpl) factory.readXML(cataURI);
		final StringBuilder buff = new StringBuilder();
		if (catalog.check(buff)) {

			for (String cata : catalogList) {
				// create
				InvCatalogRef ref = new InvCatalogRef(null,
						cata.substring(0, cata.lastIndexOf('.')), "1/"+ cata);
                catalog.removeDataset(ref);
                if ((args.length < 3) || (!args[2].equals("remove"))) {
                    catalog.addDataset(ref);
                }
			}
			catalog.finish();

		} else {
			throw new Exception(buff.toString());
		}


		// write out catalog to String
		try {

			OutputStream fout = new FileOutputStream(new File(cataURI.getPath()));

			factory.writeXML(catalog, fout, true);

			System.out.println("Final xref catalog output:" + cataURI.getPath());
			
		} catch (IOException e) {
			e.printStackTrace();
	 	}
	
	}

	private static List<String> readCatalogFile(String filename) throws IOException {
		
		return FileUtils.readLines(new File(filename));
		
	}
}
